<?php

namespace App\Handler;

use App\Anju\AdminCacher;
use App\Anju\AdminRoleCacher;
use App\Anju\MenuCacher;
use App\Anju\MenuPrivilegeCacher;
use App\Anju\RoleCacher;
use App\Anju\RoleMenuCacher;
use App\Anju\RolePrivilegeCacher;
use App\Models\Admin;
use App\Models\AdminRole;
use App\Models\Privilege;
use App\Models\Role;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/12
 * Time: 9:36
 */
class AdminHandler
{

    static public function loadAdminMenus($adminId, $toTree = true)
    {
        /**
         * @var $item AdminRole
         * @var $admin Admin
         * @var $role Role
         * @var $privilege Privilege
         */
        $admin = AdminCacher::findAdmin($adminId);
        if (empty($admin)) {
            return [];
        }
        $isSuperRole = false;
        $roleIds = AdminRoleCacher::findRoleIds($adminId);
        $menuIds = [];
        foreach ($roleIds as $roleId) {
            $role = RoleCacher::findRoleObject($roleId);
            if ($role->isSuperRole()) {
                $isSuperRole = true;
                break;
            }
            $ids = RoleMenuCacher::findMenuIds($roleId);
            if (empty($ids)) {
                continue;
            }
            $menuIds = array_merge($menuIds, $ids);
        }
        $menus = null;
        if ($isSuperRole) {
            $menus = MenuCacher::all();
        } else {
            $menuIds = MenuCacher::explanIds($menuIds);
            $menuIds = array_merge($menuIds, MenuCacher::getPublicMenuIds());
            $menus = MenuCacher::findMenus($menuIds);
        }
        if (!$toTree) {
            return $menus;
        }
        return MenuHandler::toAdminDesignMenus($menus);
    }


    static public function encodePassword($salt, $password)
    {
        $string = $salt . ":" . $password;
        return EncryptHandler::encode($string);
    }

    static public function decodePassword($salt, $password)
    {
        $string = EncryptHandler::decode($password);
        $last = str_replace($salt . ":", "", $string);
        return $last;
    }

    /**
     * @param $adminId
     * @return Admin
     */
    static public function findAdminById($adminId)
    {
        return Admin::find($adminId);
    }
}